<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Casts\Attribute;

class Position extends Model
{
    use HasFactory;

    /**
     * 表名
     */
    protected $table = 'positions';

    /**
     * 可填充的字段
     */
    protected $fillable = [
        'code',
        'name',
        'department_id',
        'department_name',
        'level',
        'category',
        'description',
        'responsibilities',
        'requirements',
        'min_salary',
        'max_salary',
        'status',
        'sort_order',
        'report_to',
        'is_management',
        'vacancy_count',
        'notes',
    ];

    /**
     * 类型转换
     */
    protected $casts = [
        'responsibilities' => 'array',
        'requirements' => 'array',
        'min_salary' => 'decimal:2',
        'max_salary' => 'decimal:2',
    ];

    /**
     * 获取岗位的员工
     */
    public function employees(): HasMany
    {
        return $this->hasMany(Employee::class, 'position_id');
    }

    /**
     * 获取岗位的部门配置
     */
    public function departmentPositions(): HasMany
    {
        return $this->hasMany(DepartmentPosition::class);
    }

    /**
     * 获取试岗设置
     */
    public function probationSettings(): HasMany
    {
        return $this->hasMany(ProbationSetting::class);
    }

    /**
     * 获取权限规则
     */
    public function permissionRules(): HasMany
    {
        return $this->hasMany(PermissionRule::class);
    }

    /**
     * 获取上级岗位
     */
    public function superior(): BelongsTo
    {
        return $this->belongsTo(Position::class, 'report_to');
    }

    /**
     * 获取下级岗位
     */
    public function subordinates(): HasMany
    {
        return $this->hasMany(Position::class, 'report_to');
    }

    /**
     * 获取岗位状态标签
     */
    protected function statusLabel(): Attribute
    {
        return Attribute::make(
            get: function () {
                return match ($this->status) {
                    'active' => '正常',
                    'inactive' => '停用',
                    'obsolete' => '废弃',
                    default => '未知',
                };
            }
        );
    }

    /**
     * 获取岗位类别标签
     */
    protected function categoryLabel(): Attribute
    {
        return Attribute::make(
            get: function () {
                return match ($this->category) {
                    'management' => '管理',
                    'technical' => '技术',
                    'operational' => '操作',
                    'support' => '支持',
                    'other' => '其他',
                    default => '未知',
                };
            }
        );
    }

    /**
     * 获取薪资范围
     */
    protected function salaryRange(): Attribute
    {
        return Attribute::make(
            get: function () {
                if ($this->min_salary && $this->max_salary) {
                    return number_format($this->min_salary, 2) . ' - ' . number_format($this->max_salary, 2);
                } elseif ($this->min_salary) {
                    return number_format($this->min_salary, 2) . ' 以上';
                } elseif ($this->max_salary) {
                    return number_format($this->max_salary, 2) . ' 以下';
                }
                return '未设置';
            }
        );
    }

    /**
     * 获取在职员工数量
     */
    protected function activeEmployeeCount(): Attribute
    {
        return Attribute::make(
            get: function () {
                return $this->employees()->active()->count();
            }
        );
    }

    /**
     * 作用域：活跃岗位
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * 作用域：管理岗位
     */
    public function scopeManagement($query)
    {
        return $query->where('is_management', true);
    }

    /**
     * 作用域：按类别筛选
     */
    public function scopeByCategory($query, string $category)
    {
        return $query->where('category', $category);
    }

    /**
     * 作用域：按层级筛选
     */
    public function scopeByLevel($query, int $level)
    {
        return $query->where('level', $level);
    }

    /**
     * 作用域：有空缺的岗位
     */
    public function scopeWithVacancy($query)
    {
        return $query->where('vacancy_count', '>', 0);
    }

    /**
     * 作用域：按薪资范围筛选
     */
    public function scopeBySalaryRange($query, float $min, float $max)
    {
        return $query->where(function ($q) use ($min, $max) {
            $q->whereBetween('min_salary', [$min, $max])
              ->orWhereBetween('max_salary', [$min, $max])
              ->orWhere(function ($q2) use ($min, $max) {
                  $q2->where('min_salary', '<=', $min)
                     ->where('max_salary', '>=', $max);
              });
        });
    }

    /**
     * 检查岗位是否需要试岗
     */
    public function requiresProbation(): bool
    {
        return $this->probationSettings()->active()->exists();
    }

    /**
     * 获取岗位试岗设置
     */
    public function getProbationSetting()
    {
        return $this->probationSettings()->active()->first();
    }

    /**
     * 获取岗位权限规则
     */
    public function getPermissionRules()
    {
        return $this->permissionRules()->active()->get();
    }
}